package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import common.ApplicationVariable;
import lombok.SneakyThrows;
import model.ResultData;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * 添加菜品
 */
@WebServlet("/adddish")
public class AddDishServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType(ApplicationVariable.RESPONSE_CONTENT_TYPE);
        int state=-1;
        int data=-1; // 受影响的行数
        String msg="未知错误!";
        // 1.得到并验证前端的参数
        String name=req.getParameter("name");
        String priceStr=req.getParameter("price");
        if(!StrUtil.isBlank(name)&&!StrUtil.isBlank(priceStr)){
            // 2.进行操作
            Connection connection= DBUtil.getConnection();
            String sql="insert into dish(name,price) values(?,?)";
            PreparedStatement statement=connection.prepareStatement(sql);
            statement.setString(1,name);
            statement.setBigDecimal(2,new BigDecimal(priceStr));
                data=statement.executeUpdate();
                state=200;
                DBUtil.close(null,statement,connection);
        }else{
            msg="参数错误！";
        }
        // 3.将操作结果返回给前端
        ResultData resultData=new ResultData();
        resultData.setState(state);
        resultData.setData(data);
        resultData.setMsg(msg);
        resp.getWriter().println(JSONUtil.toJsonStr(resultData));
    }
}
